package com.example.util;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.example.bean.Article;
import com.example.bean.BaseMessage;
import com.example.bean.TextMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;


public class JsonToMap {
	@SuppressWarnings("unchecked")
	public static Map<String,Object> jsonToMapSingle(String json){
		Map<String, Object> reMap = null;
		if(null!=json&&json.length()>0){
			ObjectMapper objectMapper = new ObjectMapper();
			try {
				reMap = objectMapper.readValue(json, Map.class);
			} catch (JsonParseException e) {
				
			} catch (JsonMappingException e) {
				
			} catch (IOException e) {
				
			}
		}
		return reMap;
	}
	private static XStream xstream=new XStream(new XppDriver(){
		public HierarchicalStreamWriter createWriter(Writer out){
			return new PrettyPrintWriter(out){
				//对所有xml节点的转换都增加CDATA标记
				boolean cdata=true;
				public void startNode(String name,Class clazz){
					super.startNode(name,clazz);
				}
				protected void writeText(QuickWriter writer,String text){
					if(cdata){
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					}else{
						writer.write(text);
					}
					
				}
			};
		}
	});
	public static String getImageText(Map<String,Object>param){
		Article art=new Article();
		art.setTitle(MapUtils.getString(param,"title"));
		art.setDescription(MapUtils.getString(param,"description"));
		art.setPicUrl(MapUtils.getString(param,"picurl"));
		art.setUrl(MapUtils.getString(param,"url"));
		xstream.alias("item",art.getClass());
		String xmlart=xstream.toXML(art);
		xmlart="<Articles>"+xmlart+"</Articles>";
		BaseMessage txt=new BaseMessage();
		txt.setCreateTime(new Date().getTime());
		txt.setFromUserName(MapUtils.getString(param,"touser"));
		txt.setToUserName(MapUtils.getString(param,"fromuser"));
		txt.setMsgType(MapUtils.getString(param,"msgtype"));
		xstream.alias("xml",txt.getClass());
		String xml=xstream.toXML(txt);
		xml=xml.replaceAll("</xml>","<ArticleCount>1</ArticleCount></xml>");
		xml=xml.replaceAll("</xml>",xmlart+"</xml>");
		System.out.println(xml);
		return xml;
	}
	public static String getText(TextMessage tx){
		xstream.alias("xml",tx.getClass());
		return xstream.toXML(tx);
	}
}
